package com.jshongli.myapplication.common.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;


import com.jshongli.myapplication.MyApplication;
import com.jshongli.myapplication.R;
import com.jshongli.myapplication.login.LoginActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;

//import com.jshongli.zhzm_sh.ui.LoginActivity;

/**
 * Created by Administrator on 2017/6/27.
 */

public class AppManager {

    private static Stack<Activity> activityStack = new Stack<Activity>();

    /**
     * 添加Activity到堆栈
     */
    public static void addActivity(Activity activity) {
        activityStack.push(activity);
    }

    /**
     * 获取当前Activity（堆栈中最后一个压入的）
     */
    public static Activity currentActivity() {
        return activityStack.lastElement();
    }

    /**
     * 结束当前Activity（堆栈中最后一个压入的）
     */
    public static void finishCurrentActivity() {
        Activity activity = activityStack.pop();
        activity.finish();
    }

    /**
     * 结束指定的Activity
     */
    public static void finishActivity(Activity activity) {
        if (activity != null) {
            for(int i = 0; i < activityStack.size() - 1; i++) {
                if (activityStack.get(i) == activity) {
                    activityStack.remove(activityStack.get(i));
                }
            }
            if(!activity.isFinishing()) {
                activity.finish();
            }
        }
    }

    /**
     * 结束指定类名的Activity
     */
    public static void finishActivity(Class<?> cls) {

        for(int i = 0; i < activityStack.size() - 1; i++) {
            if (activityStack.get(i).getClass().equals(cls)) {
                finishActivity(activityStack.get(i));
            }
        }
    }

    /**
     * 结束所有Activity
     */
    public static void finishAllActivity() {
        for (Activity activity : activityStack) {
            if (activity != null) {
                activity.finish();
            }
        }
        activityStack.clear();
    }

    public static void finishAllWithOutAppMain() {
        for (Activity activity : activityStack) {
//            if (activity != null && activity.getClass() != MainActivity.class) {
//                activity.finish();
//            }
        }
        activityStack.clear();
    }

    /**
     * 退出应用程序
     */
    public static void AppExit(Context context) {
        try {
            finishAllWithOutAppMain();
            ActivityManager manager = (ActivityManager) context
                    .getSystemService(Context.ACTIVITY_SERVICE);
            manager.killBackgroundProcesses(context.getPackageName());
            System.exit(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static boolean isExceptionDialogShow;
    private static AlertDialog.Builder exceptionBuilder;

    /**
     * show the dialog when user met some exception: such as login on another device
     */
    public static void exceptionExitToLogin(final Context context, String msg) {
        if (!isExceptionDialogShow) {
            isExceptionDialogShow = true;
            String st = context.getResources().getString(R.string.logout_notification);

            try {
                if (exceptionBuilder == null)
                    exceptionBuilder = new AlertDialog.Builder(context);
                exceptionBuilder.setTitle(st);
                exceptionBuilder.setMessage(msg);
                exceptionBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        exceptionBuilder = null;
                        isExceptionDialogShow = false;

                        UtilPreferences.removeKey(MyApplication.getInstance(), context.getString(R.string.token));
                        UtilPreferences.removeKey(MyApplication.getInstance(), context.getString(R.string.realname));
                        UtilPreferences.removeKey(MyApplication.getInstance(), context.getString(R.string.phone));
                        UtilPreferences.removeKey(MyApplication.getInstance(), context.getString(R.string.userid));
                        UtilPreferences.removeKey(MyApplication.getInstance(), context.getString(R.string.isadmin));
                        UtilPreferences.removeKey(MyApplication.getInstance(), context.getString(R.string.isqy));
                        finishAllActivity();
                        Intent intent = new Intent(MyApplication.getInstance(), LoginActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        MyApplication.getInstance().startActivity(intent);

                    }
                });
                exceptionBuilder.setCancelable(false);
                exceptionBuilder.create().show();
            } catch (Exception e) {
                Log.e("AppManager", "showExceptionDialog: " + e.getMessage() );
            }
        }
    }

    private static Map<String,Activity> destoryMap = new HashMap<>();

    /**
     * 添加到销毁队列
     *
     * @param activity 要销毁的activity
     */

    public static void addDestoryActivity(Activity activity, String activityName) {
        destoryMap.put(activityName,activity);
    }
    /**
     *销毁指定Activity
     */
    public static void destoryActivity(String activityName) {
        Set<String> keySet=destoryMap.keySet();
        for (String key:keySet){
            destoryMap.get(key).finish();
        }
    }

    public static boolean isAvilible(Context context, String packageName) {
        //获取packagemanager
        final PackageManager packageManager = context.getPackageManager();
        //获取所有已安装程序的包信息
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        //用于存储所有已安装程序的包名
        List<String> packageNames = new ArrayList<String>();
        //从pinfo中将包名字逐一取出，压入pName list中
        if (packageInfos != null) {
            for (int i = 0; i < packageInfos.size(); i++) {
                String packName = packageInfos.get(i).packageName;
                packageNames.add(packName);
            }
        }
        //判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE
        return packageNames.contains(packageName);
    }

    private boolean checkPackInfo(Context context, String packname/* packname 是要跳转的app的包名*/) {
        PackageInfo packageInfo = null;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(packname, 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return packageInfo != null;
    }

}
